package grpc

import (
	"errors"
	"fmt"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
)

func RegisterRPC(hand func(s *grpc.Server)) error {
	if viper.GetBool("debug") {
		log.Printf("注册rpc从viper读取 :::ip: %s,service-name: %s,group-name: %s,port-number: %d,weight: %d", viper.GetString("ip"), viper.GetString("service-name"), viper.GetString("group-name"), viper.GetInt("port-number"), viper.GetInt("weight"))
	}
	err := nacos.RegisterServiceInstance(viper.GetString("ip"), viper.GetString("service-name"), viper.GetString("group-name"), viper.GetInt("port-number"), viper.GetFloat64("weight"))

	if err != nil {
		return errors.New("failed to register service instance")
	}
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", viper.GetInt("port-number")))
	if err != nil {
		return errors.New("监听异常 error " + err.Error())
	}
	fmt.Println(fmt.Sprintf("监听端口: %v", viper.GetString("port-number")))
	// 2.实例化gRPC
	s := grpc.NewServer()
	hand(s)

	//反射
	reflection.Register(s)

	//健康检查
	healthCheckServer := health.NewServer()
	healthpb.RegisterHealthServer(s, healthCheckServer)

	fmt.Println("启动成功喽 赞")
	// 4.启动服务端
	s.Serve(listener)
	return nil
}
